package com.roc.web.action.reviseMerinfo;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.ReviseMerinfoBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.service.IExcelService;
import com.roc.service.ServiceException;
import com.roc.service.reviseMerinfo.ReviseMerinfoService;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

@Component
@Namespace("/reviseData")
@SuppressWarnings("serial")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class ReviseMerinfoAction extends PaginationBaseAction {

	private Logger logger = LogManager.getLogger(ReviseMerinfoAction.class);
	private ReviseMerinfoSearchCondition searchCondition;

	private File file;

	private InputStream excelFile;
	@Autowired
	private ReviseMerinfoService reviseMerinfoService;
	@Autowired
	private IPageService pageService;
	@Autowired
	private IExcelService excelService;
	@Autowired
	IPageService pagenitionService;

	/**
	 * 初始化页面
	 * @return
	 * @throws Exception
	 */
	@Action(value = "init", results = {
			@Result(name = "success", location = "/pages/reviseMerinfo/reviseMerinfoJsp.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String init() throws Exception {
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if (op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())
				|| op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())
				|| op.getRoleType().equals(Role.SYSTEM.getCode())) {
			return SUCCESS;
		}
		addActionError("无权限访问!!!");
		return ERROR;
	}

	// return SUCCESS;
	// }
	/**
	 * 批量导入初始化页面
	 * @return
	 */
	@Action(value = "importReviseJsp", results = { @Result(name = "success", location = "/pages/reviseMerinfo/importReviseMerinfo.jsp") })
	public String moreBlackList() throws Exception {
		return SUCCESS;
	}

	/**
	 * 查询
	 * @return
	 */
	@Action(value = "queryRevise", results = { @Result(name = "success", location = "/pages/reviseMerinfo/reviseMerinfoJsp.jsp") })
	public String queryRevise() throws Exception {

		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if (op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())
				|| op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())
				|| op.getRoleType().equals(Role.SYSTEM.getCode())) {
			logger.info("查询整改商户数据");
			try {
				if (searchCondition == null) {
					searchCondition = (ReviseMerinfoSearchCondition) getSearchConditionFromSession();
					if (searchCondition == null) {
						searchCondition = new ReviseMerinfoSearchCondition();
					}
				}
				searchCondition.setOpId(String.valueOf(op.getId()));// 获取当前人员ID

				int rows = pagenitionService.countSQL(searchCondition);
				if (rows > 0) {
					searchRsList = pagenitionService.findAllSQL(searchCondition,
							calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				}
				List<ReviseMerinfoBean> ReviseList = new ArrayList<ReviseMerinfoBean>();
				dealWith(ReviseList, searchRsList);

				getRequest().setAttribute("ReviseList", ReviseList);
				this.setTotalPage(this.calcuTotalPage(rows));
				getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
				getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
				addActionMessage("当前条件下统计到【" + rows + "】条记录");
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				addActionError(e.getMessage());
				return ERROR;
			}
			return SUCCESS;
		}
		addActionError("无权限访问!!!");
		return ERROR;
	}


	/**
	 * 批量导入商户号
	 * @Title: importMidList
	 * @Description: TODO
	 * @param @return
	 * @return String
	 * @throws
	 */
	@Action(value = "importMidList", interceptorRefs = {
			@InterceptorRef(value = "token"),
			@InterceptorRef(value = "rocDefaultStack", params = { "fileUpload.allowedExtensions",
					"xlsx", "fileUpload.maximumSize", "100000000" }) }, results = {
			@Result(name = "success", location = "/pages/reviseMerinfo/importReviseMerinfo.jsp"),
			@Result(name = "error", location = "/error.jsp"),
			@Result(name = "invalid.token", location = "/error.jsp") })
	public String importMidList() {
		Operators logingMerchant = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);
		try {
			Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
			resultMap = reviseMerinfoService.importMidList(file, logingMerchant);
			System.out.println(resultMap.size() + "" + resultMap.get("result"));

			if (resultMap.size() > 0) {
				addActionMessage((String) resultMap.get("result"));

			}
		} catch (ServiceException e) {
			e.printStackTrace();
			addActionError("批量导入商户号失败~");
		}
		return SUCCESS;
	}

	/**
	 * 整改商户数据--导出
	 * @Title: exportChangeCheck
	 * @Description: TODO
	 * @param @return
	 * @return String
	 * @throws
	 */
	@Action(value = "exportReviseMerinfo", results = {
			@Result(name = "success", type = "stream", params = { "contentType",
					"application/vnd.ms-excel", "inputName", "excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xls", "bufferSize", "1024*3" }),
			@Result(name = "error", location = "/pages/reviseMerinfo/reviseMerinfoJsp.jsp") })
	public String exportChangeCheck() {
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		logger.info("导出整改商户数据excel开始");

		if (searchCondition == null) {
			searchCondition = (ReviseMerinfoSearchCondition) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new ReviseMerinfoSearchCondition();
			}
		}

		try {
			searchCondition.setOpId(String.valueOf(op.getId()));

			int rows = pageService.countSQL(searchCondition);
			if (rows > 0) {
				searchRsList = pageService.findAllSQL(searchCondition,
						calcuStart(getCurrentPage()), rows);
			}
			List<ReviseMerinfoBean> revList = new ArrayList<ReviseMerinfoBean>();
			dealWith(revList, searchRsList);
			logger.info("rows:" + rows + "    searchRsList.size():" + searchRsList.size());
			HSSFWorkbook work = excelService.exportReviseMerinfoList(revList, searchCondition);

			ByteArrayOutputStream output = new ByteArrayOutputStream();
			work.write(output);

			byte[] ba = output.toByteArray();
			excelFile = new ByteArrayInputStream(ba);
			output.flush();
			output.close();

			logger.info("导出整改商户数据excel结束");
		} catch (Exception e) {
			logger.info("导出整改商户数据异常："+e);
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 将查询出来的数据封装到list
	 * @param revList
	 * @param searchRsList
	 * @return
	 * @throws ServiceException
	 */

	private List<ReviseMerinfoBean> dealWith(List<ReviseMerinfoBean> ReviseList,
			List<Object> searchRsList) throws ServiceException {
		int i = 1;
		if (searchRsList != null && searchRsList.size() > 0) {
			Iterator<?> iterator = searchRsList.iterator();
			while (iterator.hasNext()) {
				Object[] obj = (Object[]) iterator.next();
				ReviseMerinfoBean rev = new ReviseMerinfoBean();
				rev.setRowNum(String.valueOf(i)); // 序号
				rev.setMchtCd(Constance.Null2EmptyTrim(obj[1])); // 银联商户
				String termId = Constance.Null2EmptyTrim(obj[2]);
				//if (!termId.isEmpty()) {
				if (StringUtils.isNotBlank(termId)) {	
					rev.setTermId(termId);// 终端号
				} else
					rev.setTermId("此商户没有终端");// 终端号
				rev.setName(Constance.Null2EmptyTrim(obj[3]));// 43域
				rev.setNameBusi(Constance.Null2EmptyTrim(obj[4]));// 商户简称
				rev.setUcBcCd32(Constance.Null2EmptyTrim(obj[5]));// 32域
				rev.setMccCd18(Constance.Null2EmptyTrim(obj[6]));// 商户类型
				int count = reviseMerinfoService.WhetherDeal(Constance.Null2EmptyTrim(obj[1]));
				String isBusi = "";
				if (count > 0 && !"此商户没有终端".equals(rev.getTermId())) {
					isBusi = "是";
				} else {
					isBusi = "否";
				}
				rev.setIsDeal(isBusi);// 近三个月是否有交易
				rev.setUpAgent(Constance.Null2EmptyTrim(obj[7]));// 直属代理商
				rev.setOneAgent(Constance.Null2EmptyTrim(obj[8]));// 一级代理商
				rev.setOrgNum(Constance.Null2EmptyTrim(obj[9]));// 所属机构号
				rev.setCompanyid(Constance.Null2EmptyTrim(obj[10]));// 所属大区
				rev.setBusiLiceNo(Constance.Null2EmptyTrim(obj[11]));// 营业执照号
				rev.setCertif(Constance.Null2EmptyTrim(obj[12]));// 法人名称
				if(obj[13]!=null){
					Map<String, String> Province = ConfigProperties.getGBProviceProperties();
					rev.setProvCd(Province.get(Constance.Null2EmptyTrim(obj[13])));// 省
				}
				if(obj[14]!=null){
					Map<String, String> city = ConfigProperties.getGBCityProperties(Constance
							.Null2EmptyTrim(obj[13]));
					if (city.size() > 0) {
						rev.setCityCd(Constance.Null2EmptyTrim(city.get(obj[14])));// 市
					}
				}
				if(obj[15]!=null){
					Map<String, String> area = ConfigProperties.getGBAreaProperties(Constance
							.Null2EmptyTrim(obj[14]));
					if (area.size() > 0) {
						rev.setAreaCd(Constance.Null2EmptyTrim(area.get(obj[15])));// 县
					}
				}
				rev.setRegAddr(Constance.Null2EmptyTrim(obj[16]));// 商户地址
				rev.setUcBcCd32Zh(Constance.Null2EmptyTrim(obj[17]));// 实际经营地址
				rev.setContactName(Constance.Null2EmptyTrim(obj[18]));// 商户联系人姓名
				rev.setContactPhoneno(Constance.Null2EmptyTrim(obj[19]));// 商户联系人电话
				rev.setApplDate((Constance.Null2EmptyTrim(obj[20])));// 进件日期
				String status1 = Constance.Null2EmptyTrim(obj[21]);
				if ("03".equals(status1)) {
					rev.setStatus("是");// 是否冻结
				} else
					rev.setStatus("否");// 是否冻结
				rev.setRecUpdTs(Constance.Null2EmptyTrim(obj[22]));// 冻结日期
				rev.setCreateDate((Constance.Null2EmptyTrim(obj[23]).substring(0, 10)));// 冻结日期
				rev.setBatchNo(Integer.valueOf(Constance.Null2EmptyTrim(obj[24])).intValue());
				ReviseList.add(rev);
				i++;
			}
		}
		return ReviseList;
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass() throws Exception {

		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(BaseSearchCondition searchCondition)
			throws Exception {

		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(BaseSearchCondition searchCondition) {

		getSession().setAttribute(SEARCH_SESSION_REVISE_MERINFO_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {

		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_REVISE_MERINFO_QUERY);
	}

	@Override
	protected String getInitPageSize() {

		return Constance.PAGE_MAX_SIZE + "";
	}

	public ReviseMerinfoSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(ReviseMerinfoSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public String getExcelName() {
		String excelName = "商户整改数据表" + Constance.formateDate();

		try {
			excelName = new String(excelName.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			logger.info("生成excel名称失败了！");
		}

		return excelName;

	}

}